from rest_framework.generics import GenericAPIView, ListAPIView,  CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from news.models import News, Comment, Category
from news.serializers import NewsSerializer,DetailSerializer,CommentSerializer, CategorySerializer

# category
class CategoryView(GenericAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()
    def get(self,request):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset,many=True)
        return Response(serializer.data)
# self.kwargs
# /news?category_id=
class NewsView(ListAPIView):
    queryset = News.objects.all().order_by('-create_time')
    serializer_class = NewsSerializer
    pagination_class = None
    ordering_fields = ('create_time',)
    def get_queryset(self):
        a = self.request.query_params.get("category_id",None)
        if a:
            category_id = a
            print(type(category_id))
            news = News.objects.filter(category_id=category_id) # 在数据库中category为category_id
            return news
        else:
            return News.objects.all()


class NewsSingleView(GenericAPIView):
    queryset = News.objects.all()
    serializer_class = DetailSerializer

    # /news/pk/
    def get(self, request,pk):
        news = self.get_object()
        news.clicks += 1
        serializer = self.get_serializer(news)
        news.save()
        print(serializer.data)
        return Response(serializer.data)


# /news/submition
class SubmitView(CreateAPIView):
    permission_class = [IsAuthenticated]
    serializer_class = DetailSerializer


# class CommentView(GenericAPIView):
#     serializer_class = CommentSerializer
#     ordering_fields = ('create_time',)
#     def get(self,request,news_id):
#
#         queryset = Comment.objects.filter(news_id=news_id)
#         serializer = self.get_serializer(queryset,many=True)
#         return Response(serializer.data)
    # def post(self,request,news_id):
    #     data = request.data
    #     serializer = self.get_serializer(data)
    #     return Response(serializer.data) # 返回数据存在疑问

class CommentView2(APIView):

    # comment/<news_id>
    def get(self,request,news_id):
        queryset = Comment.objects.filter(news_id=news_id)
        serializer = CommentSerializer(queryset,many=True)
        return Response(serializer.data)
    # comment/sub/<news_id>
    def post(self,request,news_id):
        data = request.data
        print(data)
        serializer = CommentSerializer(data)
        return Response(serializer.data)


